package com.future.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.future.domain.Article;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

@Mapper
public interface ArticleMapper extends BaseMapper<Article> {
    /**
     * 乐观锁更新点赞数
     * @param articleId 文章ID
     * @param oldCount 旧的点赞数（用于乐观锁匹配）
     * @param newCount 新的点赞数
     * @return 影响行数（0表示更新失败）
     */
    @Update("UPDATE article SET like_count = #{newCount}, updated_at = NOW() " +
            "WHERE id = #{articleId} AND like_count = #{oldCount}")
    int updateLikeCount(@Param("articleId") Long articleId,
                        @Param("oldCount") Long oldCount,
                        @Param("newCount") long newCount);


    /**
     * 乐观锁更新收藏数
     * @param articleId 文章ID
     * @param oldCount 旧的收藏数（用于乐观锁匹配）
     * @param newCount 新的收藏数
     * @return 影响行数（0表示更新失败）
     */
    @Update("UPDATE article SET collection_count = #{newCount} " +
    " where id=#{articleId} and collection_count= #{oldCount}")
    int updateCollectionCount(@Param("articleId") Long articleId,
                              @Param("oldCount") Long oldCount,
                              @Param("newCount") long newCount);
    @Update("UPDATE article SET views = views + 1 WHERE id = #{articleId}")
    int incrementViews(@Param("articleId") Long articleId);

    /**
     * 搜索文章
     * @param page 分页参数
     * @param keyword 搜索关键词
     * @return 分页文章列表
     */
    @Select("SELECT * FROM article " +
            "WHERE is_approved = 1 " +
            "AND (title LIKE CONCAT('%', #{keyword}, '%') " +
            "     OR content LIKE CONCAT('%', #{keyword}, '%')) " +
            "ORDER BY created_at DESC")
    Page<Article> receptionSearchArticles(Page<Article> page, @Param("keyword") String keyword);
    @Select("SELECT * FROM article " +
            "WHERE (title LIKE CONCAT('%', #{keyword}, '%') " +
            "     OR content LIKE CONCAT('%', #{keyword}, '%')) " +
            "ORDER BY created_at DESC")
    Page<Article> backgroundSearchArticles(Page<Article> page, @Param("keyword") String keyword);
}
